/* loading */

var loading = {
    show: function () {
        $('#loading-frame').show();
    },
    hide: function () {
        $('#loading-frame').hide();
    }
};

/**
 * ajax获取json数据
 * @param url
 * @param data
 * @param async
 * @param successFun
 * @param errorFun
 * @returns {{}}
 */
requestJson = function (url, data, async, successFun, errorFun) {
    if (!(typeof loading === 'undefined')) {
        loading.show();
        $("input").attr("readonly", "readonly");
    }

    var responseData = {};
    responseData.status = -100;
    responseData.message = '网络不给力!';
    responseData.data = null;

    // data._csrf = $('meta[name="csrf-token"]').attr("content");

    $.ajax({
        async: async || false,
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        success: function (data) {
            responseData = data;

            if (successFun) {
                successFun(data);
            }

            if (!(typeof loading === 'undefined')) {
                loading.hide();
                $("input").removeAttr("readonly");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status == "302") {
                errorMessage("登录超时");
                window.location.href = "../site/login?return_url=" + window.location.href;
                return false;
            }

            if (!(typeof loading === 'undefined')) {
                loading.hide();
                $("input").removeAttr("readonly");
            }

            responseData.status = -101;
            responseData.message = XMLHttpRequest.responseText;

            errorMessage(responseData.message);

            if (errorFun) {
                errorFun(responseData);
            }
        }
    });

    return responseData;
};

/**
 * ajax获取HTML数据
 * @param url
 * @param data
 * @param async
 * @param successFun
 * @param errorFun
 * @returns {*}
 */
requestHtml = function (url, data, async, successFun, errorFun) {
    var responseHtml = null;

    $.ajax({
        async: async || false,
        type: "POST",
        url: url,
        data: data,
        dataType: "html",
        success: function (data) {
            responseHtml = data;

            if (successFun) {
                successFun(data);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status == "302") {
                errorMessage("登录超时");
                window.location.href = "../site/login?return_url=" + window.location.href;
                return false;
            }

            responseHtml = XMLHttpRequest.responseText;

            errorMessage(responseHtml);

            if (errorFun) {
                errorFun(responseHtml);
            }
        }
    });

    return responseHtml;
};

errorMessage = function (message) {
    var errorDialog = $('#errorModal');
    if (errorDialog.length > 0) {
        $('#errorContainer').html(message);
        $('#errorModal').modal('show');
    } else {
        alert(message);
    }
};

warningMessage = function (message) {
    var warningDialog = $('#warningModal');
    if (warningDialog.length > 0) {
        $('#warningContainer').html(message);
        $('#warningModal').modal('show');
    } else {
        alert(message);
    }
}

/**
 * 获取url中paramName参数的值
 * @param {string} url
 * @param {string} paramName
 * @returns {null}/{string} paramValue
 */
getUrlParamValue = function (url, paramName) {
    var t = url.split('?');
    if (t.length > 1) {
        var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
        var r = url.split("?")[1].match(reg);
        if (r !== null) return decodeURIComponent(r[2]);
    }
    return null;
};

/**
 * 针对url设置参数,如果url中有此参数,则修改此参数。如果url中无此参数,则新增此参数。
 * @param url
 * @param paramName
 * @param paramValue
 * @returns {string} url 设置参数后的url
 */
setUrlParam = function (url, paramName, paramValue) {
    var t = url.split('?');
    url = t[0];
    if (t.length > 1) {
        var pString = t[1];
        if (pString.length > 0) {
            var params = pString.split('&');
            var hasParam = false;
            for (var i = 0; i < params.length; i++) {
                var param = params[i].split('=');
                var pName = param[0];
                var pValue = param[1];
                if (i === 0) {
                    url += '?';
                } else {
                    url += '&';
                }
                url += pName + '=';
                if (pName === paramName) {
                    hasParam = true;
                    url += paramValue;
                } else {
                    url += pValue;
                }
            }
            if (!hasParam) {
                url += '&' + paramName + '=' + paramValue;
            }
        } else {
            url += '?' + paramName + '=' + paramValue;
        }
    } else {
        url += '?' + paramName + '=' + paramValue;
    }

    return url;
};

/**
 * 移除url中的某个参数
 * @param url
 * @param paramName
 * @returns {string} url 移除参数后的url
 */
removeUrlParam = function (url, paramName) {
    var t = url.split('?');
    url = t[0];
    if (t.length > 1) {
        var pString = t[1];
        if (pString.length > 0) {
            var params = pString.split('&');
            var pCount = 0;
            for (var i = 0; i < params.length; i++) {
                var pName = params[i].split('=')[0];
                if (pName !== paramName) {
                    if (pCount === 0) {
                        url += '?';
                    } else {
                        url += '&';
                    }
                    pCount++;
                    url += params[i];
                }
            }
        }
    }

    return url;
};

/**
 * 移除url中的所有参数
 * @param url
 * @returns {string} url 移除参数后的url
 */
removeUrlAllParams = function (url) {
    return url.split('?')[0];
};


/**
 * 弹出确认对话框
 * @param data 传入确定，取消按钮的参数
 * @param message 设置title内容，不设置为默认
 * @param okCallback 确定按钮回调事件
 * @param cancelCallback 取消按钮回调事件
 */
confirmDialog = function (data, message, okCallback, cancelCallback) {

    $("#confirmModal").find("#confirmOkBtn").unbind().click(function () {
        okCallback(data);
    });

    $("#confirmModal").find("#confirmCancelBtn").unbind().click(function () {
        if (cancelCallback) {
            cancelCallback(data);
        }
    });

    if (message) {
        $("#confirmModal").find(".modal-body").text(message);
    }

    $("#confirmModal").modal("show");
};

/**
 * 弹出消息提示框
 * @param title 设置title内容，不设置为默认
 * @param message 设置message内容，不设置为默认
 */
infoDialog = function (message, title) {
    if (title) {
        $("#infoModal").find(".modal-title").text(message);
    }

    if (message) {
        $("#infoModal").find("#infoContainer").text(message);
    }

    $("#infoModal").modal("show");
};


/**
 * 弹出错误提示框
 * @param title 设置title内容，不设置为默认
 * @param message 设置message内容，不设置为默认
 */
errorDialog = function (message, title) {
    if (title) {
        $("#errorModal").find(".modal-title").text(title);
    }

    if (message) {
        $("#errorModal").find("#errorContainer").text(message);
    }

    $("#errorModal").modal("show");
};

/**
 * 弹出警告提示框
 * @param title 设置title内容，不设置为默认
 * @param message 设置message内容，不设置为默认
 */
warningDialog = function (message, title) {
    if (title) {
        $("#warningModal").find(".modal-title").text(title);
    }

    if (message) {
        $("#warningModal").find("#warningContainer").text(message);
    }

    $("#warningModal").modal("show");
};


checkAllCheckBox = function (chk, element) {
    if ($(chk).is(':checked')) {
        element.find('input[type=checkbox]').prop("checked", true);
    } else {
        element.find('input[type=checkbox]').prop("checked", false);
    }
};


validatePassword = function (password) {
    if (password == '' || password == null) {
        errorDialog('密码不能为空');
        return false;
    }

    if ((validateLength(password, '密码', 6, 16) == false)) {
        errorDialog('密码长度在6到16位之间');
        return false;
    }
    return true;
};


validatePhone = function (phone) {
    if (phone == '' || phone == null) {
        warningDialog('号码不能为空');
        return false;
    }
    //验证规范
    if (!/^((\d{7,8})|(0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/.test(phone)) {
        return false;
    }
};


//验证邮编
validatePostCode = function (postcode) {
    if (postcode != '' && postcode != null) {
        if (!/^[1-9]\d{5}$/.test(postcode)) {
            warningDialog('邮编必须为起始数字不为0的6位数字');
            return false;
        }
    }
};

validateEmail = function (email) {
    if (email != '' && email != null) {
        if (!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(email)) {
            warningDialog('邮箱错误');
            return false;
        }
    }
};
validateQQ = function (qq) {
    if (qq != '' && qq != null) {
        if (!/^[1-9]\d{4,11}$/.test(qq)) {
            warningDialog('qq错误');
            return false;
        }
    }
};

ValidateNumber = function (number) {
    var regu = /^[0-9]+\.?[0-9]*$/;
    if (!regu.test(number)) {
        return false;
    }
    return true;
};

/**
 * 删除数组某项
 * @param dx
 * @returns {boolean}
 */
Array.prototype.remove = function (dx) {
    if (isNaN(dx) || dx > this.length) {
        return false;
    }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[dx]) {
            this[n++] = this[i];
        }
    }
    this.length -= 1;
}

Array.prototype.deleteObject = function (searchKey, searchFun) {
    var temp = new Array();
    while (this.length > 0) {
        var item = this.shift();
        if (!searchFun(item, searchKey)) {
            temp.push(item);
        }
    }

    while (temp.length > 0) {
        this.unshift(temp.pop());
    }
}

Array.prototype.clone = function () {
    return this.slice(0);
}

/**
 * 关闭模态框
 * @param modal_id
 */
function closeModal(modal_id) {
    $("#" + modal_id).modal('hide');
}

/**
 *预览多个图片
 * @param file
 */
//////定义上传方法函数

function PreviewImage(file, prevDiv) {
    if (file.files && file.files[0]) {
        var reader = new FileReader();
        reader.onload = function (evt) {
            prevDiv.append('<div class="tag-img-item upload-img-show"><img id="img_n' + n + '" src="' + evt.target.result + '" style="width: 400px;" /></div>');
            setTimeout('initMany()', 500);
        };

        reader.readAsDataURL(file.files[0]);
    }
    else {
        prevDiv.append('<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>');
    }

}

//重置表单,允许用户连续添加相同的图片
// function resetForm(imgFile){
//     $(imgFile).parent()[0].reset();
// }

//控制"按钮"显示与隐藏
$(".previewMany").off("mouseenter", "div").on("mouseenter", "div", function () {
    var that = this;
    var dom = $(that).children("a");
    dom.removeClass("hide");
    //为点击事件解绑，防止重复执行
    dom.off("click");
    dom.on("click", function () {
        //删除当前图片
        dom.parent().remove();
    });
}).off("mouseleave", "div").on("mouseleave", "div", function () {
    var that = this;
    $(that).children("a").addClass("hide");
});


//*复选框点击全选*/
checkOneCheckBox = function (obj, all_id) {
    var all_array = $(obj).attr("name");
    var checked_length = $("input[name='" + all_array + "']:checked").length;
    if (!$(obj).prop('checked')) {
        $("#" + all_id).prop('checked', false);
    } else if (checked_length != 0 && checked_length == $("input[name='" + all_array + "']").length) {
        $("#" + all_id).prop('checked', true);
    }
};

//图片上传预览
function preview(file, element_id) {
    var prevDiv = document.getElementById(element_id);
    if (file.files && file.files[0]) {
        $("#img").show();
        var reader = new FileReader();
        reader.onload = function (evt) {
            prevDiv.innerHTML = '<img src="' + evt.target.result + '" style="width: 200px;height: 200px" />';
        }
        reader.readAsDataURL(file.files[0]);
    }
    else {
        prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
    }
}

/**
 * 图片加载失败后加载error图片
 * @param element
 * @returns {boolean}
 */
function showErrorImage(element) {
    $(element).attr('src', '../../images/error-img.jpg');
    return false;
}



